package org.lds.message.center.client;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.lds.message.center.client.util.ResultDTOUtil;
import org.lds.message.center.common.Endpoint;
import org.lds.message.center.common.model.ResultDTO;
import org.lds.message.center.common.model.request.PublicRequest;
import org.lds.message.center.service.grpc.MessageCenterServiceGrpc;
import org.lds.message.center.service.grpc.PublicGrpcRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


public class GrpcClient implements Endpoint {

    private final MessageCenterServiceGrpc.MessageCenterServiceBlockingStub blockStub;
    private final MessageCenterServiceGrpc.MessageCenterServiceStub stub;

    public GrpcClient(MessageCenterServiceGrpc.MessageCenterServiceBlockingStub blockStub, MessageCenterServiceGrpc.MessageCenterServiceStub stub) {
        this.blockStub = blockStub;
        this.stub = stub;
    }

    @Override
    public ResultDTO common(PublicRequest request) {
        PublicGrpcRequest.Builder builder = PublicGrpcRequest.newBuilder();
        Map<String, PublicGrpcRequest.GrpcRequest> requestMap = buildGrpcRequestMap(request);
        if (MapUtils.isNotEmpty(requestMap)) {
            builder.putAllRequest(requestMap);
        }
        return ResultDTOUtil.toResultDTO(blockStub.common(builder.build()));
    }

    private Map<String, PublicGrpcRequest.GrpcRequest> buildGrpcRequestMap(PublicRequest request) {
        if (Objects.isNull(request)) return null;
        Map<String, List<String>> requestMap = request.getRequest();
        if (MapUtils.isEmpty(requestMap)) return null;

        Map<String, PublicGrpcRequest.GrpcRequest> map = new HashMap<>();
        requestMap.forEach((k, v) -> {
            PublicGrpcRequest.GrpcRequest grpcRequest = buildGrpcRequest(v);
            if (Objects.nonNull(grpcRequest)) {
                map.put(k, grpcRequest);
            }
        });
        return map;
    }

    private PublicGrpcRequest.GrpcRequest buildGrpcRequest(List<String> list) {
        PublicGrpcRequest.GrpcRequest.Builder builder = PublicGrpcRequest.GrpcRequest.newBuilder();
        if (CollectionUtils.isNotEmpty(list)) {
            builder.addAllRequest(list);
        }
        return builder.build();
    }

}
